//
//  ToppedCentreViewController.m
//  JiFengDaRen
//
//  Created by zhuchao on 16/3/23.
//  Copyright © 2016年 SH_iOS. All rights reserved.
//

#import "CSPayCenterViewController.h"
#import "ToppedCentreViewController.h"
typedef enum{
    WXTopped,
    UnionTopped,
    MPOSTopped
}Toppedtype;
@interface ToppedCentreViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)UIView *myBgView;
@property(nonatomic,strong)UITextField *moneyTf;
@property(nonatomic,strong)UIButton *payBtn;
@end

@implementation ToppedCentreViewController
-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
  
}


#pragma mark -- 显示扫描结果
-(void)configUI{
    self.title = @"余额充值";
    self.view.backgroundColor = KBASEBGCOLOR;
    self.myBgView = [[UIView alloc]init];
    self.myBgView.backgroundColor = [UIColor  whiteColor];
    self.myBgView.layer.borderWidth = 0.5;
    self.myBgView.layer.borderColor = KLINECOLOR.CGColor;
    
    [self.view addSubview:self.myBgView];
    [self.myBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).with.offset(__I6Height(20));
        make.left.mas_equalTo(self.view.mas_left).with.offset(0);
        make.right.mas_equalTo(self.view.mas_right).with.offset(0);
        make.height.mas_equalTo(__I6Height(44));
        
    }];
    
    self.moneyTf = [[UITextField alloc]init];
    self.moneyTf.delegate = self;
    self.moneyTf.placeholder = @"请输入充值金额";
    self.moneyTf.font = KSystemFont(__I6Width(14));
    self.moneyTf.textColor = [UIColor blackColor];
    [self.moneyTf  setValue:[UIColor colorWithHexString:@"#c0c0c7"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.moneyTf  setValue:KSystemFont(__I6Width(14)) forKeyPath:@"_placeholderLabel.font"];
    self.moneyTf.clearButtonMode = UITextFieldViewModeAlways;
    self.moneyTf.keyboardType  =   UIKeyboardTypeDecimalPad ;
    [self.myBgView addSubview:self.moneyTf];
    
    [self.moneyTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.myBgView.mas_top).with.offset(__I6Height(0));
        make.left.mas_equalTo(self.myBgView.mas_left).with.offset(__I6Width(15));
        make.right.mas_equalTo(self.myBgView.mas_right).with.offset(__I6Width(-15));
        make.height.mas_equalTo(__I6Height(44));
    }];
    
    
    
    self.payBtn = [[UIButton alloc]init];
    self.payBtn.layer.cornerRadius = __I6Width(5);
    self.payBtn.layer.masksToBounds = YES;
    [self.payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.payBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [self.payBtn setBackgroundImage:[UIImage imageNamed:@"sm_navigationbar"] forState:UIControlStateNormal];
    self.payBtn.titleLabel.font = KSystemFont(__I6Width(17));
    [self.payBtn addTarget:self action:@selector(payBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.payBtn];
    [self.payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.myBgView.mas_bottom).with.offset(__I6Height(60));
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(__I6Width(326));
        make.height.mas_equalTo(__I6Height(42));
    }];
}


#pragma mark -- 点击收款
-(void)payBtnClicked:(UIButton *)btn{
    
    [self.view endEditing:YES];
    if (self.moneyTf.text.length == 0 || [self.moneyTf.text floatValue
        ] <= 0) {
        [self.view makeToast:@"请输入充值金额" duration:2 position:@"center"];
        return;
    }
    
    MBProgressHUD *hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hud hideAnimated:YES afterDelay:1.5];
    NSDictionary *params = @{@"amount":@([self.moneyTf.text floatValue])};
    [MyDataService requestAFURL:KBalance_Recharge httpMethod:@"POST" params:params data:nil complection:^(id result) {
        
      [MBProgressHUD hideHUDForView:self.view animated:YES];

        if ([result[@"success"] isEqualToNumber:@(1)]) {
            NSNumber *orderId = result[@"data"];
            CSPayCenterViewController * paymentVc  = [[CSPayCenterViewController alloc]init];
            paymentVc.orderPayId = orderId;
            paymentVc.using_type = @(2);
            paymentVc.total_money = self.moneyTf.text;
            [self.navigationController pushViewController:paymentVc animated:YES];

        }else{
            [self.view makeToast:result[@"data"] duration:2 position:@"center"];
        }
    } failure:^(id erro) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    }];

    
    
}

- (void)showError:(NSString *)errorString
{
    
    
    [self.moneyTf resignFirstResponder];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark --- 文本框代理
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.moneyTf) {
        NSScanner      *scanner    = [NSScanner scannerWithString:string];
        NSCharacterSet *numbers;
        NSRange         pointRange = [textField.text rangeOfString:@"."];
        
        if ( (pointRange.length > 0) && (pointRange.location < range.location  || pointRange.location > range.location + range.length) )
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        }
        else
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
        }
        
        if ( [textField.text isEqualToString:@""] && [string isEqualToString:@"."] )
        {
            return NO;
        }
        
        short remain = 2; //默认保留2位小数
        
        NSString *tempStr = [textField.text stringByAppendingString:string];
        NSUInteger strlen = [tempStr length];
        if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
            if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
                return NO;
            }
            if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
                return NO;
            }
        }
        
        NSRange zeroRange = [textField.text rangeOfString:@"0"];
        if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
            if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){// 当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
                textField.text = string;
                return NO;
            }else{
                if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                    if([string isEqualToString:@"0"]){
                        return NO;
                    }
                }
            }
        }
        
        NSString *buffer;
        if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
        {
            return NO;
        }
        
    }
    return YES;
}

/*
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
    if (string.length == 0) {
        return YES;
    }
    //第一个参数，被替换字符串的range，第二个参数，即将键入或者粘贴的string，返回的是改变过后的新str，即textfield的新的文本内容
    NSString *checkStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
    //正则表达式
    NSString *regex = @"^\\-?([0-9]\\d*|0)(\\\\d{7})?$";
    return [self isValid:checkStr withRegex:regex];
}
//检测改变过的文本是否匹配正则表达式，如果匹配表示可以键入，否则不能键入
- (BOOL) isValid:(NSString*)checkStr withRegex:(NSString*)regex
{
    NSPredicate *predicte = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicte evaluateWithObject:checkStr];
}

*/

@end
